package com.yhy.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;

/**
 * describe:
 *
 * @author helloworldyu
 * @date 2018/5/8
 */
public class StringNioSocketClient {
	private final String host;
	private final int port;
	EventLoopGroup group = new NioEventLoopGroup();


	public StringNioSocketClient(String host, int port) {
		this.host = host;
		this.port = port;
	}

	public Channel open() throws Exception {
		Bootstrap b = new Bootstrap();
		b.group(group)
				.channel(NioSocketChannel.class)
				.remoteAddress(new InetSocketAddress(host,port))
				.handler(new ChannelInitializer<SocketChannel>() {
					@Override
					public void initChannel(SocketChannel ch)
							throws Exception {
						ch.pipeline()
								.addLast(new StringEncoder())
								.addLast(new StringDecoder())
								.addLast(new ServerHandler())
								.addLast(new ServerHandler2());

					}
				});
		return b.connect().sync().channel();
	}


	public void close() throws InterruptedException {
		group.shutdownGracefully().sync();
	}

	public static void main(String[] args)
			throws Exception {
		final String host = "127.0.0.1";
		final int port = 8080;

		StringNioSocketClient stringNioSocketClient = new StringNioSocketClient(host, port);
		Channel channel = stringNioSocketClient.open();
		channel.writeAndFlush(new String("nihao"));
		int read = System.in.read();
		stringNioSocketClient.close();
	}
}